package cn.nfwx.tv.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import cn.nfwx.tv.model.Result;

public abstract class ResponseCallback<E> implements ResponseWithFailListener<String> {

    // 响应正常
    @Override
    public void onResponse(String requestTag, String message) {
        Result<E> result = JSON.parseObject(message, new TypeReference<Result<E>>() {
        }.getType());
        if (result.getMessage().equals(Result.RESULT_SUCCESS)) {
            onSuccess(requestTag, result.getData());
        } else {
            onFailure(requestTag, result.getMessage());
        }
    }

    // 错误
    @Override
    public void onError(String requestTag, Throwable t) {
        onFailure(requestTag, t.getMessage());
    }

    // 结束
    @Override
    public void onFinish() {

    }

    @Override
    public void onFail(String requestTag, String response) {
        onFailure(requestTag, response);
    }

    public abstract void onSuccess(String requestTag, E response);

    public abstract void onFailure(String requestTag, String message);
}
